package xyz.xcvu.ma2.module;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.annotation.MagicModule;
import org.ssssssss.script.annotation.Comment;

import java.util.Map;


@Component
@MagicModule("mp")
public class Mp {

    @Comment("获取公众号实例")
    public WxMpService getMpService(
            @Comment("AppId") String appId,
            @Comment("Secret") String secret,
            @Comment("Token")String token,
            @Comment("AesKey")String aesKey
    ){
        WxMpService mpService = new WxMpServiceImpl();
        WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();

        configStorage.setAppId(appId);
        configStorage.setSecret(secret);
        configStorage.setToken(token);
        configStorage.setAesKey(aesKey);

        mpService.setWxMpConfigStorage(configStorage);
        return mpService;
    }

    @Comment("发送模板消息")
    public String sendTplMsg(
            @Comment("公众号实例")WxMpService mpService,
            @Comment("用户ID")String openId,
            @Comment("模板ID")String templateId,
            @Comment("分享网址")String url,
            @Comment("模板消息")Map<String, String>[] msgData
    ){
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage
                .builder()
                .toUser(openId)
                .templateId(templateId)
                .url(url)
                .build();
        for(Map<String, String> item : msgData){
            templateMessage.addData(new WxMpTemplateData(item.get("name"),item.get("value"),item.get("color")));
        }
        try {
            // 发送模板消息
            return mpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
            return e.getMessage();
        }
    }

    @Comment("微信公众号模板消息跳转小程序")
    public WxMpTemplateMessage.MiniProgram getTplMsgMini(
            String appId,
            String pagePath,
            Boolean usePath
    ){
        WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram();
        miniProgram.setAppid(appId);
        miniProgram.setPagePath(pagePath);
        miniProgram.setUsePath(usePath);
        return miniProgram;
    }
}
